import Vue from 'vue';
import { Subject } from 'rxjs';
import store from '../../store';

import './app-drawer.less';

export class AppDrawer {

    /**
     * 实例对象
     */
    private static readonly $drawer = new AppDrawer();

    /**
     * 构造方法
     */
    constructor() {
        if (AppDrawer.$drawer) {
            return AppDrawer.$drawer;
        }
    }

    /**
     * vue 实例
     *
     */
    private vueExample!: Vue;

    /**
     * 获取实例对象
     */
    public static getInstance() {
        return AppDrawer.$drawer;
    }

    /**
     * 创建 Vue 实例对象
     */
    private createVueExample(view: { viewname: string, title: string, width?: number, height?: number, placement?: any }, data: any = {}, uuid: string): Subject<any> {
        let subject = new Subject<any>();
        const div = document.createElement('div');
        div.setAttribute('id', uuid);
        document.body.appendChild(div);
        const vueExample = new Vue({
            store: store,
            el: div,
            data() {
                let data = {
                    isShow: false,
                    viewname: '',
                    tempResult: { ret: '' },
                    placement: '',
                    width: 256,
                    currentViewLevel: 0
                }
                return data;
            },
            created() {
                this.viewname = view.viewname;
                this.placement = view.placement === 'DRAWER_LEFT' ? 'left' : 'right';
                if (view.width) {
                    if (view.width.toString().indexOf('px') > 0) {
                        if (!Object.is(view.width, '0px')) {
                            this.width = parseInt(view.width.toString().slice(0, view.width.toString().length - 2));
                        } else {
                            this.width = 256;
                        }
                    } else {
                        if (view.width !== 0) {
                            this.width = view.width;
                        } else {
                            this.width = 256;
                        }
                    }
                } else {
                    this.width = 256;
                }
            },
            mounted() {
                this.isShow = true;
                if (!localStorage.getItem('viewlevel')) {
                    localStorage.setItem('viewlevel', '150');
                    this.currentViewLevel = 150;
                } else {
                    let computedViewLevel = Number(localStorage.getItem('viewlevel')) + 1;
                    localStorage.setItem('viewlevel', String(computedViewLevel));
                    this.currentViewLevel = computedViewLevel;
                }
                const _element: any = this.$el;
                _element.getElementsByClassName('ivu-drawer-mask')[0].style.zIndex = this.currentViewLevel;
                _element.getElementsByClassName('ivu-drawer-wrap')[0].style.zIndex = this.currentViewLevel;
            },
            methods: {
                close: function (result: any) {
                    if (result && Array.isArray(result) && result.length > 0) {
                        Object.assign(this.tempResult, { datas: JSON.parse(JSON.stringify(result)) });
                    }
                    this.isShow = false;
                },
                dataChange: function (result: any) {
                    this.tempResult = { ret: '' };
                    if (result && Array.isArray(result) && result.length > 0) {
                        Object.assign(this.tempResult, { ret: 'OK' }, { datas: JSON.parse(JSON.stringify(result)) });
                    }
                },
                visibleChange: function ($event: any) {
                    if (!$event) {
                        if (subject) {
                            if (this.tempResult && Object.is(this.tempResult.ret, 'OK')) {
                                subject.next(this.tempResult);
                            }
                        }
                        setTimeout(() => {
                            vueExample.$destroy();
                            document.body.removeChild(vueExample.$el);
                        }, 300);
                    }
                }
            },
            render() {
                return (
                    <drawer placement={this.placement} closable={false} v-model={this.isShow} width={this.width} on-on-visible-change={this.visibleChange}>
                        {this.viewname && !Object.is(this.viewname, '') ?
                            this.$createElement(this.viewname, {
                                class: {
                                    viewcontainer2: true,
                                },
                                props: {
                                    viewdata: JSON.stringify(data)
                                },
                                on: {
                                    viewdataschange: ($event: any) => this.dataChange($event),
                                    close: ($event: any) => this.close($event)
                                },
                            }) : ''}
                    </drawer>
                );
            }
        });
        return subject;
    }

    /**
     * 打开抽屉
     *
     * @param {({ viewname: string, title: string, width?: number, height?: number, placement?: 'DRAWER_LEFT' | 'DRAWER_RIGHT'  })} view
     * @param {*} [data={}]
     * @returns {Subject<any>}
     * @memberof AppDrawer
     */
    public openDrawer(view: { viewname: string, title: string, width?: number, height?: number, placement?: 'DRAWER_LEFT' | 'DRAWER_RIGHT'  }, data: any = {}): Subject<any> {
        try {
            const uuid = this.getUUID();
            const subject = this.createVueExample(view, data, uuid);
            return subject;
        } catch (error) {
            console.log(error);
            return new Subject<any>();
        }
    }

    /**
     * 生成uuid
     */
    private getUUID(): string {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
        }
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
    }


}